package com.loong.web.suppert.xsd.parser;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

import com.loong.tool.lang.Strings;
import com.loong.web.suppert.collection.list.KvnList.Kvn;

/**
 * Kvn解析器
 *
 * @author 张成轩
 */
public class KvnDefinitionParser implements BeanDefinitionParser {

	private static final String TYPE_STRING = "string";
	private static final String TYPE_INT = "int";

	private static final String DEFAULT_TYPE = TYPE_STRING;

	@Override
	public BeanDefinition parse(Element element, ParserContext parserContext) {

		RootBeanDefinition kvn = new RootBeanDefinition();
		// 设置类型
		kvn.setBeanClass(Kvn.class);
		// 设置id
		String id = element.getAttribute("id");
		if (Strings.isNotNull(id)) {
			BeanDefinitionHolder idHolder = new BeanDefinitionHolder(kvn, id);
			BeanDefinitionReaderUtils.registerBeanDefinition(idHolder, parserContext.getRegistry());
		}

		// 设置参数
		String key = element.getAttribute("key");
		String key_type = element.getAttribute("key-type");
		String value = element.getAttribute("value");
		String value_type = element.getAttribute("value-type");
		String name = element.getAttribute("name");
		String name_type = element.getAttribute("name-type");

		// 设置构造方法
		setConstructor(kvn, key, key_type);
		setConstructor(kvn, value, value_type);
		setConstructor(kvn, name, name_type);
		return kvn;
	}

	/**
	 * 添加到构造方法参数
	 * 
	 * @param bean 类型
	 * @param value 值
	 * @param type 值类型
	 */
	private void setConstructor(RootBeanDefinition bean, String value, String type) {

		bean.getConstructorArgumentValues()
				.addGenericArgumentValue(Strings.isNull(value) ? null : getValue(value, type));
	}

	/**
	 * 转换值类型
	 * 
	 * @param value 值
	 * @param type 值类型
	 * @return 转换后值
	 */
	private Object getValue(String value, String type) {

		if (Strings.isNull(type))
			type = DEFAULT_TYPE;
		if (TYPE_STRING.equalsIgnoreCase(type))
			return value;
		else if (TYPE_INT.equalsIgnoreCase(type))
			return Integer.parseInt(value);
		else
			throw new RuntimeException("kvn-type is not exists");
	}
}
